#!/usr/bin/python
"""
This code is taken from the activestate page, which implies
that it is free as in beer, bot offers no obvious license terms.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306

Correction: http://aspn.activestate.com/ASPN/Python/Cookbook/

Welcome to the Python Cookbook, a collaborative collection of your 
contributions to Python lore.
Python Cookbook code is freely available for use and review. We encourage 
you to contribute recipes (code and discussion), comments and ratings.

Thanks to everyone who submitted recipes and comments for the Python Cookbook
Second Edition. The collection, co-edited with Alex Martelli and 
Anna Ravenscroft, is scheduled for publication in March, 2005.

Contributors whose recipes are used in the book will receive a complimentary
copy of the Second Edition. A portion of all royalties will go to the
non-profit Python Software Foundation.

Cheers and happy cooking! 

Except where otherwise noted, recipes in the Python Cookbook are published
under the Python license .
"""

import httplib, mimetypes


def get_content_type(filename):
    return mimetypes.guess_type(filename)[0] or 'application/octet-stream'

def post_multipart(host, selector, fields, files):
    """
    Post fields and files to an http host as multipart/form-data.
    fields is a sequence of (name, value) elements for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be uploaded as files
    Return the server's response page.
    """
    content_type, body = encode_multipart_formdata(fields, files)
    h = httplib.HTTP(host)
    h.putrequest('POST', selector)
    h.putheader('content-type', content_type)
    h.putheader('content-length', str(len(body)))
    h.endheaders()
    h.send(body)
    errcode, errmsg, headers = h.getreply()
    return h.file.read()

def encode_multipart_formdata(fields, files,mimetype=None):
    """
    fields is a sequence of (name, value) elements for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be uploaded as files
    Return (content_type, body) ready for httplib.HTTP instance
    """
    BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
    CRLF = "\r\n"
    L = []
    for (key, value) in fields:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"' % key)
        L.append('')
        L.append(value.encode('ascii'))
    for (key, filename, value) in files:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
        if not mimetype:
            mimetype=(mimetypes.guess_type(filename)[0] or 'application/octet-stream')
        L.append('Content-Type: %s' % mimetype)
        #L.append('Content-Length: %s' % len(value))
        L.append('')
        L.append(value)
        #print "L %s is type %s"%(L[len(L)-1],type(L[len(L)-1]))
    L.append('--' + BOUNDARY + '--')
    L.append('')
    #body = CRLF.join(L)
    body=""
    for item in L:
        body+="%s\r\n"%item
        
    body+="\r\n"
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body
